#include "../test_impl.h"

#include "../../../include/pulsed_thread.h"
#include "../../../include/component_module.h"
#include "../../../include/mutex.h"

namespace Test
{

  class ITestServiceImpl
    : public CoClassBase
        <
          TL::TypeListAdapter
            <
              ITestService,
              IMessageMgrImpl
            >
        >
  {
  public:
    BOSS_DECLARE_STR_CLSID(TEST_ITESTMSGMGRSERVICEIMPL)

    ITestServiceImpl()
      : Period(100)
      , MsgId(0)
    {
    }

    // ITestService
    virtual TResult BOSS_CALL_TYPE Start()
    {
      ISyncObject Lock(GetSynObj());
      if (Thread.get())
        return rcFail;
      try
      {
        Thread.reset(new PulsedThread(CreateMemberCallback(*this, &ITestServiceImpl::ThreadFunc), Period));
      }
      catch (std::exception &)
      {
      }
      return rcOk;
    }
    virtual TResult BOSS_CALL_TYPE Stop()
    {
      ISyncObject Lock(GetSynObj());
      if (!Thread.get())
        return rcFail;
      Thread.reset(0);
      return rcOk;
    }

  private:
    std::auto_ptr<PulsedThread> Thread;

    unsigned Period;
    unsigned long MsgId;

    void ThreadFunc()
    {
      RefObjPtr<IMessage> Msg = IBaseImpl<IMessageImpl>::Create();
      Msg->Set(MsgId++);
      SendMsg(Msg.Get());
    }
  };

  typedef TL::TypeListAdapter
  <
    ITestServiceImpl
  >
  ExportTypeList;
}

BOSS_DECLARE_MODULE_ENTRY_POINT
(
  "TestComponent1",
  0c0fadd4-208e-4ccc-8b2a-729fa67745bc,
  Boss::Mutex,
  Test::ExportTypeList
)
